/**
 * Webpack 5 完整配置
 * 包含路径别名、API代理、开发服务器、构建优化等
 */

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const webpack = require('webpack');

module.exports = (env, argv) => {
  const isProduction = argv.mode === 'production';
  const isDevelopment = !isProduction;

  return {
    // 入口配置
    entry: {
      main: './src/main.js',
      // 多入口示例
      // admin: './src/admin.js',
      // mobile: './src/mobile.js'
    },

    // 输出配置
    output: {
      path: path.resolve(__dirname, 'dist'),
      filename: isProduction ? 'js/[name].[contenthash:8].js' : 'js/[name].js',
      chunkFilename: isProduction ? 'js/[name].[contenthash:8].chunk.js' : 'js/[name].chunk.js',
      assetModuleFilename: 'assets/[name].[contenthash:8][ext]',
      publicPath: '/',
      clean: true
    },

    // 解析配置
    resolve: {
      // 路径别名配置
      alias: {
        '@': path.resolve(__dirname, 'src'),
        '@components': path.resolve(__dirname, 'src/components'),
        '@views': path.resolve(__dirname, 'src/views'),
        '@utils': path.resolve(__dirname, 'src/utils'),
        '@assets': path.resolve(__dirname, 'src/assets'),
        '@styles': path.resolve(__dirname, 'src/styles'),
        '@api': path.resolve(__dirname, 'src/api'),
        '@store': path.resolve(__dirname, 'src/store'),
        '@router': path.resolve(__dirname, 'src/router'),
        '@config': path.resolve(__dirname, 'src/config'),
        '@types': path.resolve(__dirname, 'src/types'),
        '@hooks': path.resolve(__dirname, 'src/hooks'),
        '@constants': path.resolve(__dirname, 'src/constants'),
        '@services': path.resolve(__dirname, 'src/services'),
        '@middleware': path.resolve(__dirname, 'src/middleware'),
        '@directives': path.resolve(__dirname, 'src/directives'),
        '@filters': path.resolve(__dirname, 'src/filters'),
        '@mixins': path.resolve(__dirname, 'src/mixins'),
        '@plugins': path.resolve(__dirname, 'src/plugins'),
        '@tests': path.resolve(__dirname, 'src/tests'),
        '@mocks': path.resolve(__dirname, 'src/mocks'),
        '@locales': path.resolve(__dirname, 'src/locales'),
        '@themes': path.resolve(__dirname, 'src/themes'),
        '@layouts': path.resolve(__dirname, 'src/layouts'),
        '@modules': path.resolve(__dirname, 'src/modules'),
        '@pages': path.resolve(__dirname, 'src/pages'),
        '@widgets': path.resolve(__dirname, 'src/widgets'),
        '@features': path.resolve(__dirname, 'src/features'),
        '@shared': path.resolve(__dirname, 'src/shared'),
        '@core': path.resolve(__dirname, 'src/core'),
        '@app': path.resolve(__dirname, 'src/app'),
        '@public': path.resolve(__dirname, 'public'),
        '@node_modules': path.resolve(__dirname, 'node_modules')
      },
      
      // 文件扩展名解析
      extensions: ['.js', '.jsx', '.ts', '.tsx', '.vue', '.json', '.css', '.scss', '.sass', '.less'],
      
      // 模块解析
      modules: ['node_modules', path.resolve(__dirname, 'src')],
      
      // 解析器配置
      fallback: {
        "path": require.resolve("path-browserify"),
        "crypto": require.resolve("crypto-browserify"),
        "stream": require.resolve("stream-browserify"),
        "buffer": require.resolve("buffer"),
        "util": require.resolve("util"),
        "fs": false,
        "net": false,
        "tls": false
      }
    },

    // 模块配置
    module: {
      rules: [
        // JavaScript/TypeScript 处理
        {
          test: /\.(js|jsx|ts|tsx)$/,
          exclude: /node_modules/,
          use: [
            {
              loader: 'babel-loader',
              options: {
                presets: [
                  ['@babel/preset-env', {
                    targets: {
                      browsers: ['> 1%', 'last 2 versions', 'not ie <= 8']
                    },
                    useBuiltIns: 'usage',
                    corejs: 3
                  }],
                  '@babel/preset-react',
                  '@babel/preset-typescript'
                ],
                plugins: [
                  '@babel/plugin-proposal-class-properties',
                  '@babel/plugin-proposal-object-rest-spread',
                  '@babel/plugin-syntax-dynamic-import',
                  '@babel/plugin-transform-runtime'
                ]
              }
            }
          ]
        },

        // Vue 文件处理
        {
          test: /\.vue$/,
          use: [
            {
              loader: 'vue-loader',
              options: {
                compilerOptions: {
                  preserveWhitespace: false
                }
              }
            }
          ]
        },

        // CSS 处理
        {
          test: /\.css$/,
          use: [
            isDevelopment ? 'style-loader' : MiniCssExtractPlugin.loader,
            {
              loader: 'css-loader',
              options: {
                importLoaders: 1,
                modules: {
                  auto: true,
                  localIdentName: isDevelopment ? '[name]__[local]--[hash:base64:5]' : '[hash:base64:8]'
                }
              }
            },
            {
              loader: 'postcss-loader',
              options: {
                postcssOptions: {
                  plugins: [
                    ['autoprefixer'],
                    ['postcss-preset-env']
                  ]
                }
              }
            }
          ]
        },

        // SCSS/SASS 处理
        {
          test: /\.(scss|sass)$/,
          use: [
            isDevelopment ? 'style-loader' : MiniCssExtractPlugin.loader,
            {
              loader: 'css-loader',
              options: {
                importLoaders: 2,
                modules: {
                  auto: true,
                  localIdentName: isDevelopment ? '[name]__[local]--[hash:base64:5]' : '[hash:base64:8]'
                }
              }
            },
            {
              loader: 'postcss-loader',
              options: {
                postcssOptions: {
                  plugins: [
                    ['autoprefixer'],
                    ['postcss-preset-env']
                  ]
                }
              }
            },
            {
              loader: 'sass-loader',
              options: {
                implementation: require('sass'),
                sassOptions: {
                  includePaths: [path.resolve(__dirname, 'src/styles')]
                }
              }
            }
          ]
        },

        // Less 处理
        {
          test: /\.less$/,
          use: [
            isDevelopment ? 'style-loader' : MiniCssExtractPlugin.loader,
            {
              loader: 'css-loader',
              options: {
                importLoaders: 2,
                modules: {
                  auto: true,
                  localIdentName: isDevelopment ? '[name]__[local]--[hash:base64:5]' : '[hash:base64:8]'
                }
              }
            },
            {
              loader: 'postcss-loader',
              options: {
                postcssOptions: {
                  plugins: [
                    ['autoprefixer'],
                    ['postcss-preset-env']
                  ]
                }
              }
            },
            {
              loader: 'less-loader',
              options: {
                lessOptions: {
                  modifyVars: {
                    // 自定义主题变量
                    '@primary-color': '#1890ff',
                    '@link-color': '#1890ff',
                    '@border-radius-base': '4px'
                  },
                  javascriptEnabled: true
                }
              }
            }
          ]
        },

        // 图片处理
        {
          test: /\.(png|jpe?g|gif|svg|webp|avif)$/i,
          type: 'asset',
          parser: {
            dataUrlCondition: {
              maxSize: 8 * 1024 // 8KB
            }
          },
          generator: {
            filename: 'images/[name].[contenthash:8][ext]'
          }
        },

        // 字体处理
        {
          test: /\.(woff|woff2|eot|ttf|otf)$/i,
          type: 'asset/resource',
          generator: {
            filename: 'fonts/[name].[contenthash:8][ext]'
          }
        },

        // 音视频处理
        {
          test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)$/i,
          type: 'asset/resource',
          generator: {
            filename: 'media/[name].[contenthash:8][ext]'
          }
        },

        // 其他文件处理
        {
          test: /\.(txt|md|json|xml|yaml|yml)$/i,
          type: 'asset/source'
        }
      ]
    },

    // 插件配置
    plugins: [
      // 清理构建目录
      new CleanWebpackPlugin(),

      // HTML 模板
      new HtmlWebpackPlugin({
        template: './public/index.html',
        filename: 'index.html',
        inject: true,
        minify: isProduction ? {
          removeComments: true,
          collapseWhitespace: true,
          removeRedundantAttributes: true,
          useShortDoctype: true,
          removeEmptyAttributes: true,
          removeStyleLinkTypeAttributes: true,
          keepClosingSlash: true,
          minifyJS: true,
          minifyCSS: true,
          minifyURLs: true
        } : false
      }),

      // CSS 提取
      new MiniCssExtractPlugin({
        filename: isProduction ? 'css/[name].[contenthash:8].css' : 'css/[name].css',
        chunkFilename: isProduction ? 'css/[name].[contenthash:8].chunk.css' : 'css/[name].chunk.css'
      }),

      // 环境变量
      new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
        'process.env.API_BASE_URL': JSON.stringify(process.env.API_BASE_URL || 'http://localhost:3000'),
        'process.env.VERSION': JSON.stringify(require('./package.json').version),
        'process.env.BUILD_TIME': JSON.stringify(new Date().toISOString())
      }),

      // 复制静态资源
      new CopyWebpackPlugin({
        patterns: [
          {
            from: 'public',
            to: '.',
            globOptions: {
              ignore: ['**/index.html']
            }
          }
        ]
      }),

      // 热更新
      ...(isDevelopment ? [new webpack.HotModuleReplacementPlugin()] : [])
    ],

    // 开发服务器配置
    devServer: {
      port: 3000,
      host: '0.0.0.0',
      hot: true,
      open: true,
      compress: true,
      historyApiFallback: true,
      client: {
        overlay: {
          errors: true,
          warnings: false
        }
      },
      
      // API 代理配置
      proxy: {
        // 通用API代理
        '/api': {
          target: 'http://localhost:8080',
          changeOrigin: true,
          secure: false,
          logLevel: 'debug',
          pathRewrite: {
            '^/api': '/api'
          },
          onProxyReq: (proxyReq, req, res) => {
            console.log(`[PROXY] ${req.method} ${req.url} -> ${proxyReq.path}`);
          },
          onProxyRes: (proxyRes, req, res) => {
            console.log(`[PROXY] ${req.method} ${req.url} -> ${proxyRes.statusCode}`);
          }
        },

        // 用户服务代理
        '/api/user': {
          target: 'http://localhost:8081',
          changeOrigin: true,
          secure: false,
          pathRewrite: {
            '^/api/user': '/user'
          }
        },

        // 商品服务代理
        '/api/product': {
          target: 'http://localhost:8082',
          changeOrigin: true,
          secure: false,
          pathRewrite: {
            '^/api/product': '/product'
          }
        },

        // 订单服务代理
        '/api/order': {
          target: 'http://localhost:8083',
          changeOrigin: true,
          secure: false,
          pathRewrite: {
            '^/api/order': '/order'
          }
        },

        // 文件上传代理
        '/api/upload': {
          target: 'http://localhost:8084',
          changeOrigin: true,
          secure: false,
          pathRewrite: {
            '^/api/upload': '/upload'
          }
        },

        // WebSocket 代理
        '/ws': {
          target: 'ws://localhost:8085',
          ws: true,
          changeOrigin: true,
          secure: false
        },

        // 第三方API代理
        '/api/external': {
          target: 'https://api.external.com',
          changeOrigin: true,
          secure: true,
          pathRewrite: {
            '^/api/external': ''
          },
          headers: {
            'Authorization': 'Bearer your-token-here'
          }
        }
      },

      // 静态文件服务
      static: {
        directory: path.join(__dirname, 'public'),
        publicPath: '/'
      }
    },

    // 优化配置
    optimization: {
      minimize: isProduction,
      minimizer: [
        new TerserPlugin({
          terserOptions: {
            compress: {
              drop_console: isProduction,
              drop_debugger: isProduction
            },
            mangle: {
              safari10: true
            }
          },
          extractComments: false
        }),
        new CssMinimizerPlugin()
      ],

      // 代码分割
      splitChunks: {
        chunks: 'all',
        cacheGroups: {
          vendor: {
            test: /[\\/]node_modules[\\/]/,
            name: 'vendors',
            chunks: 'all',
            priority: 10
          },
          common: {
            name: 'common',
            minChunks: 2,
            chunks: 'all',
            priority: 5,
            reuseExistingChunk: true
          },
          styles: {
            name: 'styles',
            test: /\.(css|scss|sass|less)$/,
            chunks: 'all',
            enforce: true
          }
        }
      },

      // 运行时优化
      runtimeChunk: {
        name: 'runtime'
      }
    },

    // 性能配置
    performance: {
      hints: isProduction ? 'warning' : false,
      maxEntrypointSize: 512000,
      maxAssetSize: 512000
    },

    // 缓存配置
    cache: {
      type: 'filesystem',
      buildDependencies: {
        config: [__filename]
      }
    },

    // 开发工具
    devtool: isDevelopment ? 'eval-cheap-module-source-map' : 'source-map',

    // 统计信息
    stats: {
      colors: true,
      modules: false,
      children: false,
      chunks: false,
      chunkModules: false
    }
  };
};
